﻿using System;
using System.Linq;
using Hjt212Parser;
using HpSocketIotGateway.Db.Code1st;
using log4net;

namespace HpSocketIotGateway.Facade
{
    public class BizSendCtrCmd
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(BizSendCtrCmd));
        public static void Send()
        {
            try
            {
                using (var ctx = new GatewayContext())
                {                  
                    var list = ctx.send_ctr_cmd.Where(t => !t.is_sent).OrderByDescending(t => t.send_time).Take(1000).ToList();
                    if (list == null && list.Count < 1) return;
                    foreach (var sendMsg in list)
                    {
                        bool sentSuccess = BufferFacade.SendMsgToClient(sendMsg.mn, sendMsg.send_string);
                        ThreadUtil.Sleep(2000);
                        sendMsg.rtn_9011 = sentSuccess ? "ON" : "OFF";
                        sendMsg.rtn_9012 = sentSuccess ? "ON" : "OFF";
                        sendMsg.rtn_9014 = sentSuccess ? "ON" : "OFF";
                        sendMsg.is_sent = true;
                        sendMsg.sent_time = DateTime.Now;
                    }
                    ctx.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }
    }
}

